package com.deng.mail.authserver.mailauthserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deng.mail.authserver.mailauthserver.entity.Member;
import com.deng.mail.authserver.mailauthserver.exception.PhoneExistException;
import com.deng.mail.authserver.mailauthserver.exception.UserNameExistException;
import com.deng.mail.authserver.mailauthserver.mapper.MemberMapper;
import com.deng.mail.authserver.mailauthserver.service.IMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deng.mail.authserver.mailauthserver.vo.UserRegisterVo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 会员 服务实现类
 * </p>
 *
 * @author deng
 * @since 2022-12-22
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    @Override
    public void register(UserRegisterVo vo) {
        checkUserNameExist(vo.getUserName());
        checkPhoneExist(vo.getPhone());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        Member member = Member.builder().username(vo.getUserName())
                .mobile(vo.getPhone())
                .password(encode)
                .createTime(LocalDateTime.now()).build();
        this.save(member);
    }

    private void checkPhoneExist(String phone) {
//        List<Member> mobile = this.list(new QueryWrapper<Member>().eq("mobile", phone));
//        if (!mobile.isEmpty()) {
//            throw new PhoneExistException();
//        }
        long mobile = this.count(new QueryWrapper<Member>().eq("mobile", phone));
        if (mobile > 0L) {
            throw new PhoneExistException();
        }
    }

    private void checkUserNameExist(String userName) {
//        List<Member> username = this.list(new QueryWrapper<Member>().eq("username", userName));
//        if (!username.isEmpty()) {
//            throw new UserNameExistException();
//        }
        long username = this.count(new QueryWrapper<Member>().eq("username", userName));
        if (username > 0L) {
            throw new UserNameExistException();
        }
    }

}
